<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#canvas {
				display: block;
				margin: 0 auto;
				box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
			}
		</style>
	</head>
	<body>
		<canvas id="canvas"></canvas>
		<script type="text/javascript">
			class Ball {
				constructor(props) {
					this.x = 0;
					this.y = 0;
					this.r = 25;
					this.fillStyle = 'rgba(65,168,99,1)';
					this.strokeStyle = 'rgba(0,0,0,0)';
					Object.assign(this,props)
					return this
				}
				render(ctx){
					var {x,y,r,fillStyle,strokeStyle,vx} = this
					// 保存绘图环境
					ctx.save()
					// 将画布坐标移动到x，y
					ctx.translate(x,y)
					
					ctx.fillStyle = fillStyle;
					ctx.strokeStyle = strokeStyle;
					ctx.beginPath()
					ctx.arc(0,0,r,0,2*Math.PI,false)
					ctx.fill()
					ctx.stroke()
					// 恢复绘图环境
					ctx.restore()
					return this
				}
			}
		</script>
		<script type="text/javascript">
			var canvas = document.querySelector('#canvas')
			var ctx = canvas.getContext('2d');

			var w = canvas.width = 500;
			var h = canvas.height = 300

			
			var ball = new Ball({x:w/2,y:h/2}).render(ctx);
			// 角度
			var angle = 0;
			// 摇摆值
			let swing = 160;
			(function move(){
				window.requestAnimationFrame(move)
				// 清空画布
				ctx.clearRect(0,0,w,h)
				// 每次自加0.02
				angle+=0.02;
				// 并且%上2Π，Math.sin(angle)的值就会0->1->0->-1的值进行切换
				angle%=2*Math.PI
				ball.x = w/2 + Math.sin(angle) * swing;
				ball.render(ctx)
			})()
		</script>
	</body>
</html>
